app.controller('pingjia-page', function ($scope, $http) {
    $scope.returnError=function(){
        var pageIndex=sessionStorage.getItem('pageIndex')
        if(pageIndex==1){
            location.href='#home'
        }else if(pageIndex==2){
            location.href='#index-hot'
        }
        else if(pageIndex==3){
            location.href='#homenewest'
        }
        return;
    }
    //页面控制js
    $scope.buyNow = function () {
        var show = document.getElementsByClassName('alert-all')[0];
        show.style.display = 'block';
        $scope.comment();

    };
    $scope.buyNo = function () {
        var show = document.getElementsByClassName('alert-all')[0];
        show.style.display = 'none';
    };
    var num = finalnum = tempnum = 0;
    var lis = document.getElementsByTagName("li");
    var scoreTips = document.getElementsByClassName("score-tip")[0];
    //num:传入点亮星星的个数
//finalnum:最终点亮星星的个数
//tempnum:一个中间值
    $scope.sumStar = function (num) {
        finalnum = num || tempnum;//如果传入的num为0，则finalnum取tempnum的值
        for (var i = 0; i < lis.length; i++) {
            lis[i].className = i < finalnum ? "light" : "";//点亮星星就是加class为light的样式
        }
        $scope.num = finalnum;

    };
    for (var i = 1; i <= lis.length; i++) {
        lis[i - 1].index = i;
        lis[i - 1].onmouseover = function () { //鼠标经过点亮星星。
            $scope.sumStar(this.index);//传入的值为正，就是finalnum
        };
        lis[i - 1].onmouseout = function () { //鼠标离开时星星变暗
            $scope.sumStar(0);//传入值为0，finalnum为tempnum,初始为0
        };
        lis[i - 1].onclick = function () { //鼠标点击,同时会调用onmouseout,改变tempnum值点亮星星
            tempnum = this.index;
        }

    }

    var token = localStorage.getItem('token');
    var classId = sessionStorage.getItem('classId');
    //评价信息
    $scope.commonInfo = [];
    $scope.page = 1;

//得到评论信息
    $scope.getCommonInfo = function (page) {
        $scope.page = page ? page : 1;

        // 若该加载为初始化加载，即没有传入page参数
        if (!page) {
            $scope.page = 1;
        }

        $http({
            method: 'get',
            url: app.netPath + '/comments/show',
            headers: {Authorization: token},
            params: {commentClassId: classId, page: $scope.page}
        }).then(function (res) {
            console.log(res.data);
            var infiniteScroll = $('.infinite-scroll');
            var infiniteScrollPreloader = $('.infinite-scroll-preloader');
            if (!res.data.error) {
                for (var i = 0; i < res.data.data.length; i++) {
                    //将动态逐条存入（dynamicInfos）数组
                    $scope.commonInfo.push(res.data.data[i]);
                    //放置评价用户头像
                    if (res.data.data[i].commentUser.userAvatarAddress) {
                        res.data.data[i].commentUser.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].commentUser.userAvatarAddress;
                        app.buildImageUrl(res.data.data[i].commentUser,'userAvatarAddress',function () {
                            $scope.$digest();
                        });
                    }
                    //放置评价图片

                    if (res.data.data[i].commentImg) {

                        //得到每条评价的图片数组
                        var commentImgs = $scope.getcommentImg(res.data.data[i].commentImg);
                        var cimgs = [];
                        res.data.data[i].cimgs = cimgs;
                        if (commentImgs instanceof Array && commentImgs.length > 0) {
                            for (var j = 0; j < commentImgs.length; j++) {
                                var img = app.netPath + '/resources/commentImg/' + commentImgs[j];
                                if (commentImgs[i] == null || img == null || img == '')
                                    continue;
                                var imgObject = {
                                    imgSrc: img,
                                    isLoad: false
                                };
                                app.buildImageUrl(imgObject,'imgSrc',function () {
                                    $scope.$digest();
                                });
                                cimgs.push(imgObject);
                            }
                        }


                        // var makeItTrue = function (p, o, img) {
                        //     img.onload = function () {
                        //         $scope.commonInfo[p].cimgs[o].isLoad = true;
                        //         $scope.$digest();
                        //     }
                        // };
                        //
                        //
                        // for (var p = 0; p < $scope.commonInfo.length; p++) {
                        //     for (var o = 0; o < $scope.commonInfo[p].cimgs.length; o++) {
                        //         var image = new Image();
                        //         makeItTrue(p, o, image);
                        //         // image.onload = function () {
                        //         //     $scope.taskInfo.imgAddresses[p].isLoad = true;
                        //         //     $scope.$digest();
                        //         // };
                        //         image.src = $scope.commonInfo[p].cimgs[o].imgSrc;
                        //     }
                        //
                        // }
                    }
                }
                // 启用无限加载事件
                $.attachInfiniteScroll(infiniteScroll);
                // 启用提示符
                infiniteScrollPreloader.show();
                var thispage = $scope.commonInfo.length % 15 == 0 ? $scope.commonInfo.length / 15 : $scope.commonInfo.length / 15 + 1;
                if (res.data.allPage <= thispage) {
                    // 加载完毕，则注销无限加载事件，以防不必要的加载
                    $.detachInfiniteScroll(infiniteScroll);
                    // 删除加载提示符
                    infiniteScrollPreloader.hide();
                }
            }


            $scope.isOnloading = false;

            if (res.data.error) {
                // 删除加载提示符
                infiniteScrollPreloader.hide();
            }
        }, function () {
            $.toast('网络走丢了！')
        });


    };

    //判断是否登录
    $scope.comment = function () {
        if (!token) {
            $.toast('跳转登录', 1000);

            location.href = '#user-login'
        }
    };
    $scope.pushComment = function () {
        var commentImgString = "";
        //判断是否上传有图片
        if ($scope.commentImgList.length > 0) {
            //按规则将图片数组转化为string
            for (var i = 0; i < $scope.commentImgList.length; i++) {
                if (i == $scope.commentImgList.length - 1) {
                    commentImgString = commentImgString + $scope.commentImgList[i];
                } else {
                    commentImgString = commentImgString + $scope.commentImgList[i] + ',';
                }
            }

        }

        $scope.comsInfo = {
            commentContent: $scope.commentContent,
            commentClassId: classId,
            commentScore: $scope.num,
            commentImg: commentImgString
        };
        $http({
            method: 'post',
            url: app.netPath + '/comments/comment/add',
            headers: {Authorization: token},
            data: $scope.comsInfo
        }).then(function (res) {
            if (!res.data.error) {
                $.toast('评价成功');
                location.href = '#pingjia-page'
            } else {
                $.toast(res.data.msg);
            }
        })
    };
    //定义图片存放数组
    $scope.commentImgList = [];
    //单次提交图片的函数
    //参数为传入的一个文件类型input
    $scope.img_upload = function (files) {

        console.log('ready to upload img.');

        if (!token) {
            return;
        }

        if (!files || !files[0]) {
            console.log('文件为空');

            return;
        }

        //规定上传到服务器图片的大小
        var needHeight = 300;
        var needWidth = 300;

        //规定略缩图大小
        var smallWidth = needWidth * 0.33;

        //FileReader用来读取本地文件
        var reader = new FileReader();

        //实例化图片用于被加载在画布上
        var img = new Image();

        // 破除一个协议
        img.setAttribute("crossOrigin", 'Anonymous');

        //声明一个画布对象，当图片上传成功后添加到数组中便于显示
        var img_obj = {};

        //获取当前时间戳作为画布唯一id
        img_obj.id = new Date().getTime();

        //自动刷新双向绑定，预防双向绑定失效
        $scope.$digest();

        //获取预览画布
        var canvas = document.createElement('canvas');
        canvas.width = needWidth;
        canvas.height = needHeight;


        //控制略缩图大小
        canvas.style.width = smallWidth + 'px';

        var ctx = canvas.getContext("2d");

        //当图片加载完毕执行动作
        reader.onload = function () {

            // 通过 reader.result 来访问生成的 DataURL
            img.src = reader.result;

            img.onload = function () {

                //获取图片的高宽
                var width = img.width;
                var height = img.height;

                //获取需要使用的矩形图片区域
                var real_width = width * needHeight / needWidth > height ? height * needWidth / needHeight : width;
                var real_height = width > height * needWidth / needHeight ? height : width * needHeight / needWidth;

                //console.log('need:'+real_width+' '+real_height);
                //console.log('real:'+width+' '+height);

                //定位使图片居中
                var img_x = (width - real_width) / 2;
                var img_y = (height - real_height) / 2;

                //在画布上渲染头像预览
                ctx.drawImage(img, img_x, img_y, real_width, real_height, 0, 0, needWidth, needHeight);

                //将画布渲染的图像转换为base64字符串储存在data中
                var data = canvas.toDataURL();
                // console.log(data);


                //发送POST请求
                $http({

                    method: 'post',
                    url: app.netPath + "/comments/image-upload",
                    headers: {'Authorization': token},
                    data: data

                }).then(function (res) {
                    console.log(res.data);

                    if (!res.data.error) {
                        console.log(res.data.data);
                        //封装路径显示图片
                        $scope.commentImg = app.netPath + '/resources/commentImg/' + res.data.data;
                        //当图片上传成功添加图片显示节点
                        $("#commentImgList").append("<img src=" + $scope.commentImg + ">");
                        //存入刚上传成功的图片名称
                        $scope.commentImgList.push(res.data.data);

                    } else {
                        $.toast('错误代码：' + res.data.error + "," + res.data.msg);
                    }


                }, function () {
                    $scope.img_del(index);
                    $.toast('网络或设置错误');
                });
                //清除原来画布内容
                ctx.clearRect(0, 0, needWidth, needHeight);
            };


        };


        //加载选中的图片
        reader.readAsDataURL(files[0]);
    };

    //评论图片分割（","）
    $scope.getcommentImg = function (commentImgString) {
        var commentImgList = commentImgString.split(',');
        return commentImgList;
    };
});